<?php
class UsersController extends AppController {

	var $name = 'Users';

	var $permissions = array(
				'add_admin' => array('admin'),
				'add_manag' => array('admin'),
				'add_user' => array('admin','manag'),
				'add_emplo' => array('admin','manag'),
				'index' => array('admin'),
				'admin' => array('admin'),
				'manag' => array('admin','manag'),
				'emplo' => array('admin','emplo'),
				'view' => array('admin','manag','users','emplo'),
				'edit' => array('admin','manag','users','emplo'),
				'delete' => array('admin'),	
				'login' => '*',
				'register' => '*'
	);
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->autoRedirect = false;
		if(!empty($this->data) && isset($this->data['User']['email']) && is_numeric($this->data['User']['email'])){
			$this->data['User']['id'] = $this->data['User']['email'];
			$this->Auth->fields = array('username' => 'id', 'password' => 'password');
		}else{
			$this->Auth->fields = array('username' => 'email', 'password' => 'password');
		}
		
		$this->layout = 'cms';
	}
	
	public function beforeRender(){
		parent::beforeRender();
	}
	
	
	/**
	 * 
	 * głowna strona My Vindcharter
	 * 1. dla zalogowanych przekierowuje do view
	 * 2. dla niezalogowanych welcome
	 */
	public function welcome(){
		if (!empty($this->data)) {
		
			$this->transaction->begin($this);
		
			$password =  $this->data['User']['user_password'];	// nie zaszyfrowane hasło do wysłania klientowi
			// 			debug($this->data['User']['user_password']); die;
			if(!empty($password)){
				$this->data['User']['password'] =  $this->Auth->password($this->data['User']['user_password']);
		
			}
				
			$this->data['User']['status'] = 1;
			$this->data['User']['group'] = 'users';
			$this->User->set( $this->data );
			if ($this->User->validates()) {
					
				$this->User->create();
				if ($this->User->save($this->data)) {
		
		
					$user_['User']['email'] = $this->data['User']['email'];
					$user_['User']['password'] = $this->data['User']['password'];
		
					if($this->Auth->login($user_)){
						$user = $this->User->findById($this->Auth->user('id'));
						$this->Session->write("User",$user);
					}
					$this->transaction->commit($this);
					$this->Session->setFlash(__('The customer has been saved', true));
						
					// 					$this->redirect(array('plugin'=>false,'controller'=>'pages','action'=>'display'));
		
				} else {
					$this->data['User']['password'] = $password;
					$this->Session->setFlash(__('The customer could not be saved. Please, try again.', true));
					$this->transaction->rollback($this);
				}
		
			} else {
				$this->data['User']['password'] = $password;
				$this->Session->setFlash(__('The customer could not be saved. Please, try again.', true));
				$this->transaction->rollback($this);
			}		
		
		}		
		switch($this->Session->read('Auth.User.group')){
			case 'admin':
				$this->redirect(array('plugin'=>null,'controller' => 'users', 'action' => 'index'));
				break;
			case 'manag':
				$this->redirect(array('plugin'=>null,'controller' => 'users', 'action' => 'view'));
				break;
			case 'users':
				$this->redirect(array('plugin'=>null,'controller' => 'users', 'action' => 'view'));
				break;
		}
		
	}
	
	
	function login(){
		$this->layout = 'cms';
		
		if(!empty($this->data)){
			$this->Auth->login($this->data);
			// kiedy logujemy się z formularza dodawania produktu
			if(isset($this->params['named']['booking']) && $this->params['named']['booking'] == 1 ){
				if($this->Session->check('Auth.User.id')){
					$user = $this->User->findById($this->Auth->user('id'));
					$this->Session->write("User",$user);
				}else{
					$this->Session->setFlash(__('The user could not login. Please, try again.', true));
					$this->data['User']['password'] = "";
				}
			}

			
			if($this->Session->check('Auth.User.id')){
				$user = $this->User->findById($this->Auth->user('id'));
				$this->Session->write("User",$user);
				
				switch($this->Session->read('Auth.User.group')){
					case 'admin':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'users', 'action' => 'admin');
						break;
					case 'manag':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'users', 'action' => 'manag');
						break;
					case 'users':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'users', 'action' => 'user');
						break;
				}
				
				$this->redirect($this->Auth->loginRedirect);
			}else{
				$this->Session->setFlash(__('The user could not login. Please, try again.', true));
				$this->data['User']['password'] = "";
			}
			
		}
		
	}
	
	function logout() {
		$this->Session->delete("User");
		$this->Session->delete("Auth");
		$this->Session->delete('Store');
		$this->Session->delete('Timeline',array());
	
		$this->Session->setFlash(__('You have been successfully logged out of website.', true));
		$this->redirect($this->Auth->logout());
	}
	
	function register($params = array('status'=>1,'group'=>'users')) {
		$this->layout = 'default';
		if(!empty($this->data)) {
			$this->transaction->begin($this);
	
			$password = $this->Password->get();	// nie zaszyfrowane hasło do wysłania klientowi
			$this->data['User']['password'] =  $this->Auth->password($password);
			$this->data['User']['status'] = $params['status'];
			$this->data['User']['group'] = $params['group'];
			$this->User->set( $this->data );
			if ($this->User->validates()) {
					
				$this->User->create();
				if ($this->User->save($this->data)) {

							
						$user_['User']['email'] = $this->data['User']['email'];
						$user_['User']['password'] = $this->data['User']['password'];
	
						if($this->Auth->login($user_)){
							$user = $this->User->findById($this->Auth->user('id'));
							$this->Session->write("User",$user);
						}
						$this->transaction->commit($this);
						$this->Session->setFlash(__('The new account was created successfully', true));
						$this->redirect(array('plugin'=>false,'controller'=>'pages','action'=>'display'));

				} else {
					$this->Session->setFlash(__('New account could not be create. Please, try again.', true));
					$this->transaction->rollback($this);
				}
	
			} else {
				$this->Session->setFlash(__('New account could not be create. Please, try again.', true));
				$this->transaction->rollback($this);
			}
		}
	}
	
	function index($user_type = null) {
		if(is_null($user_type)){
			$this->Session->setFlash(__('Pleas select user type before display users list', true));
			$this->redirect($this->referer());
		}
		$this->User->recursive = 0;		
		if($user_type == 'admin') $this->set('admin', $this->User->find('all',array('conditions'=>array('User.group'=>'admin'))));
		if($user_type == 'users') $this->set('users', $this->User->find('all',array('conditions'=>array('User.group'=>'users'))));		
		if($user_type == 'manag') $this->set('providers', $this->User->find('all',array('conditions'=>array('User.group'=>'manag'))));
		if($user_type == 'emplo') $this->set('emplo', $this->User->find('all',array('conditions'=>array('User.group'=>'emplo'))));
		$this->set('user_typ',$user_type);
	}
	
	function admin() {
		$this->User->recursive = 0;
	}
	function manag() {
		$this->User->recursive = 0;
	}
	function user() {
		$this->User->recursive = 0;
	}
	
	function status($id = null){
		$this->autoRender = false;
	
		if( $this->Session->read('Auth.User.group') == 'admin'){
			$status = $this->User->field('status',array('User.id'=>$id));
				
			$this->User->id = $id;
			$this->User->saveField('status', !$status);
			$this->redirect($this->referer());
		}else{
			$this->Session->setFlash(__('You can\'t change agreement', true));
			$this->redirect($this->referer());
		}
		$this->layout = 'cms';
	}

	function view($id = null) {
	
		if($id != null && $id != $this->Auth->user('id') && $this->Auth->user('group') != 'admin'){
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect('/');
		}
		
		$id = (is_null($id)) ? $this->Auth->user('id') : $id;

		if (!empty($this->data)) {
    		$this->transaction->begin($this);
			if(isset($this->data['User']['new_password']) && isset($this->data['User']['old_password']) && !empty($this->data['User']['new_password']) && !empty($this->data['User']['old_password'])){		
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['old_password'])){
					
					$new_password = $this->Auth->password($this->data['User']['new_password']);
					$this->data['User']['password'] =  $new_password;

				}else{
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					return;	
				}
			}
			
			if(isset($this->data['User']['email_password']) && !empty($this->data['User']['new_email']) && !empty($this->data['User']['new_email'])){
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['email_password'])){
					$this->data['User']['old_email'] =  $this->data['User']['email']; // save old e-mail
					$this->data['User']['email'] =  $this->data['User']['new_email'];			
				}else{
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					return;
				}
			}
						

			$this->User->set( $this->data );
			if ($this->User->validates()){
				if ($this->User->save($this->data)){
					
					$this->transaction->commit($this);
    				$this->Session->setFlash(__('The new data has been updated. Thank you.', true));
    				
				} else {
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					$this->transaction->rollback($this);
				}	
			} else {
				$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
				$this->transaction->rollback($this);
			}
		}
		
		
		if($this->Auth->user('group') == 'users'){


		}						
		
		$this->User->recursive = 2;
		$this->data = $this->User->read(null, $id);
		

		$this->set('user_id',$id);
	}

	function add_user() {
		if (!empty($this->data)) {
			$this->data['User']['group'] = 'users';
			
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
				
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect($this->referer());
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
			$this->data['User']['password'] = '';
		}
	}
	
	function add_emplo() {
		if (!empty($this->data)) {
			$this->data['User']['group'] = 'emplo';
				
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
	
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect($this->referer());
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
			$this->data['User']['password'] = '';
		}
	}

	function add_manag() {
		if (!empty($this->data)) {
				
			$this->data['User']['group'] = 'manag';
				
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
	
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect($this->referer());
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
	}
	
	function add_admin() {
		if (!empty($this->data)) {
	
			$this->data['User']['group'] = 'admin';
	
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
	
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect($this->referer());
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
	}
	
	function edit($id = null) {
			$id = (is_null($id)) ? $this->Auth->user('id') : $id;
		
			if (!empty($this->data)) {
    		$this->transaction->begin($this);
			if(isset($this->data['User']['new_password']) && isset($this->data['User']['old_password']) && !empty($this->data['User']['new_password']) && !empty($this->data['User']['old_password'])){		
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['old_password'])){
					
					$new_password = $this->Auth->password($this->data['User']['new_password']);
					$this->data['User']['password'] =  $new_password;

				}else{
					$this->Session->setFlash(__('Problem z zapisaniem danych.', true));
					return;	
				}
			}
			
			if(isset($this->data['User']['email_password']) && !empty($this->data['User']['new_email']) && !empty($this->data['User']['new_email'])){
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['email_password'])){
					$this->data['User']['old_email'] =  $this->data['User']['email']; // save old e-mail
					$this->data['User']['email'] =  $this->data['User']['new_email'];			
				}else{
					$this->Session->setFlash(__('Problem z zapisaniem danych.', true));
					return;
				}
			}
						

			$this->User->set( $this->data );
			if ($this->User->validates()){
				if ($this->User->save($this->data)){
					
					$this->transaction->commit($this);
    				$this->Session->setFlash(__('Nowe dane zostały zapisanie pomylnie', true));
    				
				} else {
					$this->Session->setFlash(__('Problem z zapisaniem danych.', true));
					$this->transaction->rollback($this);
				}	
			} else {
				$this->Session->setFlash(__('Problem z zapisaniem danych.', true));
				$this->transaction->rollback($this);
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}

		$this->set('user_id',$id);
		$group_ = Configure::read('Config.users_groups');
		foreach ($group_ as $key => $value) {
			$groups[$key] = $value['name'];
		}
		$this->set('groups',$groups);
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	public function new_password(){
	
		if(!empty($this->data) && isset($this->data['User']['email'])){
			$user = $this->User->findByEmail($this->data['User']['email']);
			if(!is_array($user)){
				$this->Session->setFlash(__("You have entered the wrong address e-mial",true));
				$this->redirect($this->referer());
			}
			$new_password = $this->Password->get();
			$user['User']['password'] = $this->Auth->password($new_password);
			$this->User->id = $user['User']['id'];
			if($this->User->save($user)){
				$user['User']['password'] = $new_password;
				$this->data = $user;
				$this->Email->to = $user['User']['email'];
				$this->Email->bcc = array('bok@21w.pl');
				$this->Email->subject = __("New Vindcharter password.",true);
				$this->Email->replyTo = $user['User']['email'];
				$this->Email->from = $_SERVER['HTTP_HOST'].' <info@vindcharter.se>';
				$this->Email->template = 'new-password';
				$this->Email->sendAs = 'both'; // text; html; both;
	
				if ( $this->Email->send() ) {
					$this->Session->setFlash(__("Password has been reset. Please check your email.",true));
				} else {
					$this->Session->setFlash(__("Error sending. Please, try again.",true));
				}
				$this->redirect($this->referer());
			}
		}
	}
	
	public function change_password($user_id = null){
		if (empty($this->data)) {
			$this->User->recursive = 0;
			$this->data = $this->User->read(null, $user_id);
		}
		$this->set('user_id',$user_id);
	}	
	


}
